<template>
<div class="advanced-search-box">
    <Form
      :model="modeForm"
      ref="modeForm"
      :rules="ruleValidate"
      label-position="right"
      :label-width="120"
    >
    <div v-if="createbtnShow && fromPage == 'creater'">
      <PartitionTitle title="任务安排"></PartitionTitle>
      <Row :gutter="10" class="code-row-bg">
          <Col span="12" style="border: none">
            <Form-item :label="'大类:'"  prop="stype">
              <Select transfer filterable clearable v-model="modeForm.stype">
                <Option @click.native="stypeChange(item.key)" v-for="item in categoryInitiatives" :value="item.key" :key="item.key">{{
                  item.value
                }}</Option>
              </Select>
            </Form-item>
          </Col>

          <Col span="12" style="border: none">
            <Form-item :label="'小类:'"  prop="mtype">
              <Select transfer filterable clearable v-model="modeForm.mtype">
                <Option  v-for="item in detailsInitiatives" :value="item.key" :key="item.key">{{
                  item.value
                }}</Option>
              </Select>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10" class="code-row-bg">
          <Col span="12">
            <Form-item :label="'重要程度:'" prop="importance">
              <Select transfer v-model="modeForm.importance" clearable>
                <Option v-for="item in importist" :value="item.key" :key="item.key">{{
                  item.value
                }}</Option>
              </Select>
            </Form-item>
          </Col>

          <Col span="12">
            <Form-item :label="'责任部门:'" prop="dpart">
              <Select transfer v-model="modeForm.dpart" clearable multiple>
                <Option v-for="item in departList" :value="item.key" :key="item.key">{{
                  item.value
                }}</Option>
              </Select>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="重点任务:" prop="highTask">
              <Input v-model="modeForm.highTask" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="落实举措：" prop="taskMode">
              <Input v-model="modeForm.taskMode" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="预期成果：" prop="taskPreRs">
              <Input v-model="modeForm.taskPreRs" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="指标名称:" prop="indexName">
              <Input v-model="modeForm.indexName" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="指标说明和计算方法:" prop="indexCalculationMethod">
              <Input v-model="modeForm.indexCalculationMethod" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <Row :gutter="10">
        <Col span="24">
            <Form-item label="本年度预期指标值:" prop="expectedIndicator">
              <!-- <InputNumber v-model="modeForm.expectedIndicator"  :min="0" :step="0.5" style="width: 50%;"></InputNumber> -->
              <Input v-model="modeForm.expectedIndicator" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="请输入"></Input>
            </Form-item>
          </Col>
      </Row>

      <!-- <Row :gutter="20">
        <Col span="24">
          <Form-item label="成果关键指标:" prop="keyIndex">
            <Table :columns="columns" :data="tabData" border>
              <template slot-scope="{ row }" slot="name">
                <Form-item  prop="indexName">
                  <Input v-model="modeForm.indexName" placeholder="请输入"></Input>
                </Form-item>
              </template>

              <template slot-scope="{ row }" slot="method">
                <Form-item prop="indexCalculationMethod">
                  <Input v-model="modeForm.indexCalculationMethod" placeholder="请输入"></Input>
                </Form-item>
              </template>

              <template slot-scope="{ row }" slot="expect">
                <Form-item prop="expectedIndicator" style="width: 100%;">
                  <InputNumber v-model="modeForm.expectedIndicator"  :min="0" :step="0.5"></InputNumber>
                </Form-item>
              </template>
            </Table>
          </Form-item>
        </Col>
      </Row> -->

      <PartitionTitle title="权限配置"></PartitionTitle>
      <Row :gutter="20" v-if="isEdit">
        <Col span="12">
          <Form-item label="任务排序编号:" prop="taskSortNumber">
            <Input v-model="modeForm.taskSortNumber"  placeholder="请输入"></Input>
          </Form-item>
        </Col>
      </Row>

      
        <Row :gutter="10">
          <Col span="12">
            <Form-item label="填写权限:" prop="submitter">
              <Select transfer v-model="modeForm.submitter" clearable>
                <Option v-for="item in submitterList" :value="item.userId" :key="item.userId">{{
                  item.userName
                }}</Option>
              </Select>
            </Form-item>
          </Col>

          <Col span="12">
            <Form-item label="审批权限:" prop="approver">
              <Select transfer v-model="modeForm.approver" clearable>
                <Option v-for="item in approverList" :value="item.userId" :key="item.userId">{{
                  item.userName
                }}</Option>
              </Select>
            </Form-item>
          </Col>
        </Row>
      </div>
    </Form>
    <div class="foot-btn-box">
      <RPButton text="取消" @click="handleClose"/>
      <RPButton text="保存" ghost  @click="handleSubmit('save')" v-if="!isEdit"/>
      <RPButton optType="create" type="info" text="确定" @click="handleSubmit('confirm')"/>
    </div>
</div>

</template>

<script>
import {importist,departList } from '../dataConfig.js'
import PartitionTitle from '@/components/common/PartitionTitle.vue'
import coverApi from '@/api/cover'
export default {
  name: 'advancedSearch',
  props: {
    categoryInitiatives: {
      type: Array,
      default: () => []
    },
    allDataFlagList: {
      type: Array,
      default: () => []
    },
    createbtnShow: {
      type: Boolean,
      default: true
    },
    useApiGetData: {
      type: Boolean,
      default: true
    },
    fromPage: {
      type: String,
      default() {
        return "";
      }
    },
    isEdit:{
      type: Boolean,
      default() {
        return true;
      }
    },
    id:{
      type: String,
      default() {
        return "";
      }
    }
  },
  components: {
    PartitionTitle
  },
  data() {
    // const validatekeyIndex = (rule, value, callback) => {
    //   if (!this.modeForm?.indexName || !this.modeForm?.indexCalculationMethod || !this.modeForm?.expectedIndicator) {
    //       callback(new Error('请输入成果关键指标'));
    //   } else {
    //       callback();
    //   }
    // };
    const checkExpectedIndicator = (rule, value, callback) => {
      console.log(this.modeForm,"this.modeFormthis.modeForm")
      if (!value) {
        callback(new Error('请输入本年度预期指标值'));
      } else {
        callback();
      }
    };
    const checkDpart = (rule, value, callback) => {
      console.log(this.modeForm,"this.modeFormthis.modeForm")
      if (!value?.length) {
        callback(new Error('请选择责任部门'));
      } else {
        callback();
      }
    };
    return {
      detailsInitiatives:[],
      departList,
      importist,
      reason:'',
      reasons:[
        {text: '1', value: '1'},
        {text: '2', value: '2'},
        {text: '3', value: '3'},
        {text: '4', value: '4'}
      ],
      year:'',
      approverList:[],
      submitterList:[],
      modeForm: {
        stype: null,
        mtype: null,
        highTask: '',
        importance: '',
        dpart:[],
        taskMode:"",
        taskPreRs:"",
        indexName:"",
        indexCalculationMethod:"",
        expectedIndicator:"0",
        taskSortNumber:"",
        approver:"",
        submitter:""
      },
      advancedCategoryInitiatives:[],
      advancedDetailsInitiatives:[],
      taskdescList:[
        {text: '是', value: '是'},
        {text: '否', value: '否'},
        {text: '--', value: '--'}
      ],
      currentStatusList: [
        {text: '未启动', value: '未启动'},
        {text: '正常进行', value: '正常进行'},
        {text: '超额推进', value: '超额推进'},
        {text: '延期进行', value: '延期进行'},
        {text: '已完成', value: '已完成'},
        {text: '--', value: '--'}
      ],
      optionss:{
        disabledDate(date){
          const disabledDate = date.getFullYear()
          return ( disabledDate > 2025 || disabledDate < 2021 )
        },
      },
      ruleValidate:{
        stype: [
          { required: true, message: '请选择大类', trigger: 'change' }
        ],

        mtype: [
          { required: true, message: '请选择小类', trigger: 'change' }
        ],

        highTask: [
          { required: true, message: '请输入重点内容', trigger: 'blur' }
        ],

        importance: [
          { required: true, message: '请选择重要程度', trigger: 'change' }
        ],
        dpart: [
          { required: true,type:"array" ,validator: checkDpart, trigger: 'change' }
        ],
        taskMode: [
          { required: true, message: '请输入落实举措', trigger: 'blur' }
        ],
        taskPreRs: [
          { required: true, message: '请输入逾期成果', trigger: 'blur' }
        ],

        indexName: [
          { required: true, message: '请输入指标名称', trigger: 'blur' }
        ],

        indexCalculationMethod: [
          { required: true, message: '请输入指标说明和计算方法', trigger: 'blur' }
        ],

        expectedIndicator: [
          { required: true,type: 'number',validator: checkExpectedIndicator, trigger: 'change' }
        ],
        taskSortNumber:[
        { required: true, message: '请输入任务排序编号', trigger: 'blur' }
        ],
        submitter: [
          { required: true, message: '请选择填写权限', trigger: 'change' }
        ],
        approver: [
          { required: true, message: '请选择审批权限', trigger: 'change' }
        ],
        // keyIndex:[ { validator: validatekeyIndex , trigger: 'blur' }]
      },
      tabData: [
          {
            name: '',
            method: '',
            expect: ''
          }
      ],
      columns: [
          {
            title: '指标名称',
            key: 'name',
            slot: 'name'
          },
          {
            title: '指标说明和计算方法',
            key: 'method',
            slot: 'method'
          },
          {
            title: '本年度预期指标值',
            key: 'expect',
            slot: 'expect'
          }
      ],
    }
  },
  created() {
      this.getApproverList();
      this.getSubmitterList();
      this.$emit("SetTitle", "新增重点任务");
      if(this.isEdit){
        this.getHighTaskDetail();
        this.$emit("SetTitle", "编辑重点任务");
      }
      this.$emit("SetPageMinHeight", 300);
      this.$emit("SetPageWidth", 900);
    //  this.$emit("SetPageActions", [
    //   {
    //     text: '取消',
    //     handle: () => {
    //       this.$emit("Close",false);
    //     }
    //   },
    //   {
    //     text: '重置',
    //     handle: () => {
    //       this.reset();
    //     }
    //   },
    //   {
    //     text: '确定',
    //     theme: "warning",
    //     handle: () => {
    //       this.advancedSearch();
    //     }
    //   },
    // ]);
     this.advancedCategoryInitiatives = this.categoryInitiatives
     this.advancedDetailsInitiatives = this.detailsInitiatives
     this.modeForm = Object.assign({}, this.advancemodeForm) 
     if (this.modeForm.taskQuarter){
        const tq = this.modeForm.taskQuarter.split('-',2)
        this.year = new Date(tq[0])
        this.reason = tq[1]
     } else{
        this.year = ''
        this.reason = ''
     }
  },

  watch: {
    'modeForm.stype': {
      handler(val) {
        if (!val) {
          this.advancedDetailsInitiatives = []
          this.modeForm.mtype = ''
        }
      }
    }
  },
  methods: {
    handleClose() {
      this.$emit("Close",false);
    },

    //获取详情
    getHighTaskDetail(){
      coverApi.getHighTaskById({id:this.id}).then(res => {
        if(res?.data?.code == 200 && res?.data?.data){
          this.modeForm = res?.data?.data;
          this.modeForm.dpart = this.modeForm.dpart.split(',');
          if(this.modeForm.stype){
            this.getGroupMtypeList(this.modeForm.stype)
          }
        }else{
          this.modeForm = {};
        }
      })
    },

    //获取审批权限列表
    getApproverList(){
      coverApi.approverList().then(res => {
        if(res?.data?.code == 200 && res?.data?.data?.length){
          this.approverList = res?.data?.data;
        }else{
          this.approverList = [];
        }
      })
    },

    //获取填写权限列表
    getSubmitterList(){
      coverApi.submitterList().then(res => {
        if(res?.data?.code == 200 && res?.data?.data?.length){
          this.submitterList = res?.data?.data;
        }
        else{
          this.submitterList = [];
        }
      })
    },

    //校验
    handleSubmit(type) {
      this.$refs["modeForm"].validate(valid => {
        if (valid) {
          this.modeForm.dpart = this.modeForm.dpart.join();
          if(type == "save"){
            this.handleSave()
          }
          else if(type == "confirm"){
            if(this.isEdit){
              this.handleEdit()
            }
            else{
              this.handleConfirm()
            }
          }
        }
      })
    },

    //保存
    handleSave(){
      coverApi.savetHighTask(this.modeForm).then(res => {
        if(res?.data?.code == 200){
          this.$Message.success({
            content: res?.data?.data || "保存成功",
            duration: 3
          });
          this.$emit('Close', true)
        }else{
          this.$Message.error({
            content: res?.data?.msg || "保存失败",
            duration: 3
          });
        }
      })
    },

    //确定提交
    handleConfirm(){
      coverApi.insertHighTask(this.modeForm).then(res => {
        if(res?.data?.code == 200){
          this.$Message.success({
            content: res?.data?.data || "新增成功",
            duration: 3
          });
          this.$emit('Close', true)
        }
        else{
          this.$Message.error({
            content: res?.data?.msg || "新增失败",
            duration: 3
          });
        }
      })
    },

    //确定编辑
    handleEdit(){
      const params = {
        ...this.modeForm,
        id:this.id
      }
      coverApi.editHighTask(params).then(res => {
        if(res?.data?.code == 200){
          this.$Message.success({
            content: res?.data?.data || "编辑成功",
            duration: 3
          });
          this.$emit('Close', true)
        }else{
          this.$Message.error({
            content: res?.data?.msg || "编辑失败",
            duration: 3
          });
        }
      })
    },

    advancedSearch(){
      if(this.year && this.reason){
        let yearDate = this.year.getFullYear()
        this.modeForm.taskQuarter = yearDate + '-' + this.reason
      }else {
        this.modeForm.taskQuarter = ''
      }
      this.$emit("Close",this.modeForm)
    },

    stypeChange(key) {
      this.modeForm.mtype = ''
      this.getGroupMtypeList(key)
    },

    //获取小类
    getGroupMtypeList(key){
      coverApi.getGroupMtype({code:key}).then(res => {
        if(res?.data?.code == 200 && res.data?.data?.length){
          this.detailsInitiatives = res.data.data
        }
        else{
          this.detailsInitiatives = []
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
.advanced-search-box {
  .foot-btn-box {
    padding-top: 30px;
    text-align: right;
    button {
      margin-left: 10px;
    }
    .primary-button {
        color: #fff;
        background-color: #ff6f4b;
        border-color: #ff6f4b;
        font-size: 80;
    }
  }
  /deep/.core-modal-footer {
    padding: 0;
  }
  
  .Selecequarters{
    display:flex;
    
  
    /deep/.ivu-form-item-content{
          margin-left: 2px;
          width: 200px;
  
    }
  }
}
</style>

